#!/usr/bin/env python
# coding: utf-8

"""
云片api短信发送
"""

import http.client
import urllib.parse
import json
from app.config.settings import YUNPIAN


class YunPian:

    def __init__(self):
        self.apikey = YUNPIAN['key']
        self.url = YUNPIAN['url']
        self.host = YUNPIAN['host']
        self.port = YUNPIAN['port']
        self.headers = {"Content-type": "application/x-www-form-urlencoded",
                        "Accept": "text/plain"}

    def encode_args(self, args):
        """格式化自定义参数为字符串
        """
        return urllib.parse.urlencode(args)

    def tpl_send(self, mobile, tpl, args, timeout=30):
        '''
        调用云片api发送模板短信
        tpl: 模板名称
        args：模板参数
        '''
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=timeout)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "tpl_id": tpl,
            "tpl_value": args,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", self.url['tpl'], data, headers=self.headers)
            response = conn.getresponse()
            result = json.loads(response.read())
            if result['code'] == 0:
                res_msg = 'Send tpl msg to %s success by yunpian api' % mobile
            else:
                status = 'error'
                res_msg = 'Send tpl msg to %s fail by yunpian api，code %s' % (mobile, result['code'])
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            res_msg = 'Send tpl msg to %s fail by yunpian api，error info: %s' % (mobile, error_info)

        return status, res_msg

    def normal_send(self, mobile, text, timeout=30, v2=False):
        """
        调用云片api智能匹配模板发送
        """
        url = "/v2/sms/single_send.json" if v2 is True else self.url['normal']
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=timeout)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "text": text,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", url, data, headers=self.headers)
            response = conn.getresponse()
            _res = response.read()
            result = json.loads(_res.decode())
            if result['code'] == 0:
                res_msg = 'Send normal msg to %s success by yunpian api' % mobile
            else:
                status = 'error'
                res_msg = 'Send normal msg to %s fail by yunpian api，code %s' % (mobile, result['code'])
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            res_msg = 'Send normal msg to %s fail by yunpian api，error info: %s' % (mobile, error_info)

        return status, res_msg

    def normal_send_with_no_limit(self, mobile, text, timeout=30):
        """
        无限制调用云片api智能匹配模板发送
        """
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=timeout)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "text": text,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", self.url['normal'], data,
                         headers=self.headers)
            response = conn.getresponse()
            result = json.loads(response.read())
            if result['code'] == 0:
                res_msg = 'Send normal msg to %s success by yunpian api' % mobile
            else:
                status = 'error'
                res_msg = 'Send normal msg to %s fail by yunpian api，code %s' % (mobile, result['code'])
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            res_msg = 'Send normal msg to %s fail by yunpian api，error info: %s' % (mobile, error_info)

        return status, res_msg

    def get_short_url(self, long_url, name=None, timeout=30):
        """生成短链接"""
        url = "/v2/short_url/shorten.json"
        headers = {
            "Accept": "application/json;charset=utf-8",
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
        }
        params = {
            "apikey": self.apikey,
            "long_url": long_url
        }
        if name:
            params.update({"name": name})
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=timeout)
        data = self.encode_args(params)
        status = 'success'
        result = {}
        try:
            conn.request("POST", url=url, body=data, headers=headers)
            response = conn.getresponse()
            result = json.loads(response.read())
            if result['code'] == 0:
                res_msg = 'Get short url %s success by yunpian api' % long_url
            else:
                status = 'error'
                res_msg = 'Get short url %s fail by yunpian api，code %s' % (long_url, result['code'])
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            res_msg = 'Get short url %s fail by yunpian api，error info: %s' % (long_url, error_info)
        return status, res_msg, result


if __name__ == "__main__":
    # 测试将手机号改为自己手机号进行测试
    mobile = ''
    yunpian = YunPian()
    text = f"【ScanV】ScanV官网（https//www.scanv.com）于2024-01-26 10:00:00 周期性监测中发现7个疑似篡改事件，请及时修复。"
    s, m = yunpian.normal_send(mobile, text, v2=False)
    print(s, m)

